<template>
	<view>
		<view class="content" :style="{ marginTop: statusBarTop + 'rpx' }">
			<u-calendar v-model="dateShow" :mode="dateMode" @change="change"></u-calendar>
			<view class="wrap">
				<u-row gutter="16" align="center">
					<u-col span="3">
						<view style="display: flex;justify-content: space-between;">
							<view>
								<u-avatar :src="avatar" show-sex="true" :sex-icon="sexOfAvatar" size="60"
									@click="pageToMine()"></u-avatar>
							</view>
							<view style="display: flex;justify-content: flex-end;margin-right: 20rpx;">
								<u-image width="55rpx" height="55rpx" :src="iconSrc" @click="openMusic()"></u-image>
							</view>
						</view>
					</u-col>
					<u-col span="6">
						<!-- <u-search placeholder="请输入搜索内容" v-model="searchValue" input-align="center" :show-action="false"
							border-color=" #dcdfe6" @search="search()"></u-search> -->
						<view>
							<u-input v-model="groupValue" type="select" :border="false" @click="groupActionShow = true"
								input-align="center" />
							<u-action-sheet :list="groupActionSheetList" v-model="groupActionShow" :cancel-btn="false"
								@click="groupActionSheetCallback"></u-action-sheet>
						</view>
					</u-col>
					<u-col span="3"></u-col>
				</u-row>
				<u-row gutter="16" align="center">
					<u-subsection :list="navList" :current="currentNav" @change="changeContentType"></u-subsection>
					<u-subsection :list="dateList" :current="currentDate" @change="changeDateType"></u-subsection>
					<swiper class="swiper" :current="currentNav" @change="swiperChange">
						<swiper-item class="swiper-item">
							<scroll-view scroll-y class="scroll-view-swiper" @scrolltolower="loadMoreData">
								<Daily :query="queryDaily" @openImage="openImage"></Daily>
							</scroll-view>
						</swiper-item>
						<swiper-item class="swiper-item">
							<scroll-view scroll-y class="scroll-view-swiper" @scrolltolower="loadMoreData">
								<Eating :query="queryEating" @openExtend="openExtend"></Eating>
							</scroll-view>
						</swiper-item>
						<swiper-item class="swiper-item">
							<scroll-view scroll-y class="scroll-view-swiper" @scrolltolower="loadMoreData">
								<Whispers :query="queryMoney" @refresh="refresh"></Whispers>
							</scroll-view>
						</swiper-item>
						<swiper-item class="swiper-item">
							<scroll-view scroll-y class="scroll-view-swiper" @scrolltolower="loadMoreData">
								<Bill :query="queryBill" @openBillAction="openBillAction"></Bill>
							</scroll-view>
						</swiper-item>
					</swiper>
				</u-row>
			</view>
			<!-- <u-tabbar :list="tabbar" :mid-button="true"></u-tabbar> -->
		</view>
		<view class="fix-refresh-button-view">
			<button @click="clickToRefresh()" class=".fix-refresh-button"><u-icon name="reload" size="60"
					color="#2979ff"></u-icon></button>
		</view>
		<u-action-sheet :list="dailyActionList" v-model="dailyActionShow" :cancel-btn="false"
			@click="settingOfDailyOption"></u-action-sheet>
		<u-action-sheet :list="billActionList" v-model="billActionShow" :cancel-btn="false"
			@click="settingOfBillOption"></u-action-sheet>
		<u-mask :show="whispersShow" @click="whispersShow = false">
			<view class="moneyWarp">
				<view class="moneyRect" @tap.stop>
					<view class="moneyTitle">{{whispersTitle}}</view>
					<view class="moneyContent">
						<u-form-item label="去向:" label-width="150" v-if="!isUpdate">
							<u-input v-model="whispersFormData.consumptionTitle" type="text" :border="false"
								placeholder="吃什么好吃呢？" confirm-type="next" />
						</u-form-item>
						<u-form-item label="金额:" label-width="150" v-if="!isUpdate">
							<input v-model="whispersFormData.consumptionTotal" type="digit" placeholder="花多少钱钱呢？"
								:border="false" placeholder-style="color: #c0c4cc;" />
						</u-form-item>
						<u-form-item label="额度来源:" label-width="150" v-if="isUpdate">
							<u-input v-model="whispersFormData.updateTitle" type="text" :border="false"
								placeholder="注明额度来源呢？" confirm-type="next" />
						</u-form-item>
						<u-form-item label="充电额度:" label-width="150" v-if="isUpdate">
							<input v-model="whispersFormData.updateMoney" type="digit" placeholder="提多少额度呢？"
								:border="false" placeholder-style="color: #c0c4cc;" />
						</u-form-item>
						<view class="button-group">
							<u-button type="success" size="medium" @click="addConsumption()"
								style="margin-right: 20rpx;">完成</u-button>
							<u-button v-if="isSuccess && !isUpdate" type="primary" size="medium"
								@click="updateConsumption()">启用预算</u-button>
						</view>
					</view>
				</view>
			</view>
		</u-mask>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		getGroupList
	} from '@/api/bot/group'
	import {
		updateBillCell
	} from '@/api/bot/bill'
	import {
		addDailyLike,
		getDailyLikeList
	} from '@/api/bot/daily'
	import {
		addConsumption
	} from '@/api/bot/consumption'
	export default {
		data() {
			return {
				// 下边栏
				tabbar: [],
				// 屏幕顶部尺寸
				menuButton: 0,
				statusBarTop: 0,
				// 图标
				iconSrc: '/static/images/music/music.png',
				// 日期展示
				dateShow: false,
				// 图片预览集合
				content: '',
				// 日期样式
				dateMode: 'date',
				// 顶部搜索框
				searchValue: '',
				// 导航栏
				navList: [{
						name: '日常'
					},
					{
						name: '干饭'
					},
					{
						name: '钱袋子'
					},
					{
						name: '清单'
					}
				],
				// 日常操作栏
				dailyActionList: [{
					text: '点赞',
					color: '#19be6b',
					subText: '汉堡也为您点赞！'
				}, {
					text: '评论',
					subText: '汉堡提醒您，善言结善缘！'
				}],
				// 日常操作栏展示
				dailyActionShow: false,
				// 当前选择的日常
				currentDaily: '',
				// 当前选择的内容分类
				currentNav: 0,
				// 日期栏
				dateList: [{
						name: '全部'
					},
					{
						name: '日期'
					}
				],
				// 当前选择的日期
				currentDate: 0,
				// 内容查询参数
				dateSearchValue: '',
				searchValue: '',
				queryDaily: {
					pageNum: 1,
					pageSize: 10,
					refresh: 0,
					dateSearchValue: '',
					searchValue: '',
				},
				queryEating: {
					pageNum: 1,
					pageSize: 10,
					refresh: 0,
					dateSearchValue: '',
					searchValue: '',
				},
				queryBill: {
					pageNum: 1,
					pageSize: 10,
					refresh: 0,
					dateSearchValue: '',
					searchValue: '',
				},
				queryMoney: {
					pageNum: 1,
					pageSize: 10,
					refresh: 0,
					dateSearchValue: '',
					searchValue: '',
				},
				// 钱袋子功能：消费提额
				whispersTitle: '记录你的钱钱去向',
				// 钱袋子功能：消费提额展示
				whispersShow: false,
				// 钱袋子功能：消费提额表单
				whispersFormData: {},
				// 清单功能：更新状态
				isSuccess: false,
				isUpdate: false,
				// 清单操作栏
				billActionList: [{
					text: '已完成',
					color: '#19be6b',
				}, {
					text: '待完成',
					color: '#fa3534',
				}],
				// 清单操作栏展示
				billActionShow: false,
				// 清单小项
				currentItem: '',
				// 清单大项
				currentBill: '',
				groupList: [],
				groupValue: '共享圈子',
				groupActionSheetList: [{
					text: '共享圈子',
					subText: '我们大家的圈子👪',
					id: 0
				}],
				groupActionShow: false
			}
		},
		onPullDownRefresh() {
			this.reset()
			if (this.currentNav == 0) {
				this.resetDaily()
			}
			if (this.currentNav == 1) {
				this.resetEating()
			}
			if (this.currentNav == 2) {
				this.resetMoney()
			}
			if (this.currentNav == 3) {
				this.resetBill()
			}
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1500)
		},
		created() {
			// 1.获取屏幕可使用宽度
			let windowWidth = uni.getSystemInfoSync().windowWidth;
			// 2.获取状态栏高度
			const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			// 3.获取胶囊按钮位置信息
			const menuButton = uni.getMenuButtonBoundingClientRect();
			// 4.计算出导航栏高度  换算成rpx
			let navHeight = (menuButton.height + (menuButton.top - statusBarHeight) * 2) * (750 / windowWidth);
			// 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx'; 
			this.statusBarTop = statusBarHeight * (750 / windowWidth) - 10;
			this.menuButton = menuButton.bottom + menuButton.height + statusBarHeight;
		},
		onLoad() {
			this.verifiedExistGroup()
			this.tabbar = this.$store.state.tabbar;
		},
		onShow() {
			this.getGroupList()
			if (this.$store.state.refresh) {
				if (this.$store.state.publishContentType || this.$store.state.publishContentType == 0) {
					this.currentNav = this.$store.state.publishContentType
				}
				uni.startPullDownRefresh()
			}
			this.$store.commit('IS_REFRESH', false)
		},
		computed: {
			avatar() {
				return this.$store.getters.avatar
			},
			sexOfAvatar() {
				const sex = this.$store.getters.sex
				if (sex === '0') {
					return 'man';
				} else if (sex === '1') {
					return 'woman';
				} else {
					return ''
				}
			}
		},
		watch: {
			whispersShow() {
				if (this.whispersShow == false) {
					this.whispersTitle = '记录你的钱钱去向'
					this.isSuccess = false
					this.isUpdate = false
				}
			}
		},
		methods: {
			resetDaily() {
				this.queryDaily.pageNum = 1;
				this.queryDaily.refresh++;
				this.queryDaily.searchValue = ''
				this.queryDaily.dateSearchValue = ''
			},
			resetEating() {
				this.queryEating.pageNum = 1;
				this.queryEating.refresh++;
				this.queryEating.searchValue = ''
				this.queryEating.dateSearchValue = ''
			},
			resetMoney() {
				this.queryMoney.pageNum = 1;
				this.queryMoney.refresh++;
				this.queryMoney.searchValue = ''
				this.queryMoney.dateSearchValue = ''
			},
			resetBill() {
				this.queryBill.pageNum = 1;
				this.queryBill.refresh++;
				this.queryBill.searchValue = ''
				this.queryBill.dateSearchValue = ''
			},
			verifiedExistGroup() {
				let that = this
				uni.getStorage({
					key: 'groupIdByIndex',
					success: (res) => {
						let data = JSON.parse(res.data);
						let query = {
							isPage: false
						}
						getGroupList(query).then(res => {
							const result = res.rows.some(item => item.id == data.id);
							if (result) {
								this.groupValue = data.text;
							} else {
								uni.setStorage({
									key: 'groupIdByIndex',
									data: JSON.stringify(this.groupActionSheetList[0])
								});
							}
						});
					},
					fail() {
						that.groupValue = that.groupActionSheetList[0].text;
						uni.setStorage({
							key: 'groupIdByIndex',
							data: JSON.stringify(that.groupActionSheetList[0])
						});
					}
				});
			},
			getGroupList() {
				this.groupActionSheetList = [{
					text: '共享圈子',
					subText: '我们大家的圈子👪',
					id: 0
				}]
				let query = {
					isPage: false
				}
				getGroupList(query).then(res => {
					this.groupList = res.rows
					res.rows.forEach(element => {
						let temp = {
							text: element.groupName,
							id: element.id
						}
						this.groupActionSheetList.push(temp);
					})
				})
			},
			groupActionSheetCallback(index) {
				this.groupValue = this.groupActionSheetList[index].text;
				uni.setStorage({
					key: 'groupIdByIndex',
					data: JSON.stringify(this.groupActionSheetList[index])
				});
				setTimeout(() => {
					this.resetDaily()
					this.resetEating()
					this.resetMoney()
					this.resetBill()
				}, 500)
			},
			loadMoreData() {
				// 判断是否已经触底
				if (this.isScrollToLower()) {
					// 执行加载更多数据的操作
					if (this.currentNav == 0) {
						this.queryDaily.pageNum++;
					}
					if (this.currentNav == 1) {
						this.queryEating.pageNum++;
					}
					if (this.currentNav == 2) {
						this.queryMoney.pageNum++;
					}
					if (this.currentNav == 3) {
						this.queryBill.pageNum++;
					}
				}
			},
			isScrollToLower() {
				const scrollView = uni.createSelectorQuery().in(this).select('.scroll-view-swiper');
				return new Promise((resolve, reject) => {
					scrollView.boundingClientRect(rect => {
						scrollView.scrollOffset(offset => {
							resolve(offset.scrollTop + rect.height >= rect
								.scrollHeight);
						}).exec();
					}).exec();
				});
			},
			reset() {
				this.searchValue = '';
				this.dateSearchValue = '';
				this.currentDate = 0;
			},
			update(type) {
				if (this.currentNav == 0) {
					if (type == 'search') {
						this.queryDaily.searchValue = this.searchValue;
					}
					if (type == 'date') {
						this.queryDaily.dateSearchValue = this.dateSearchValue;
					}
					if (type = 'change') {
						this.queryDaily.searchValue = this.searchValue;
						this.queryDaily.dateSearchValue = this.dateSearchValue;
					}
				}
				if (this.currentNav == 1) {
					if (type == 'search') {
						this.queryEating.searchValue = this.searchValue;
					}
					if (type == 'date') {
						this.queryEating.dateSearchValue = this.dateSearchValue;
					}
					if (type = 'change') {
						this.queryEating.searchValue = this.searchValue;
						this.queryEating.dateSearchValue = this.dateSearchValue;
					}
				}
				if (this.currentNav == 2) {
					if (type == 'search') {
						this.queryMoney.searchValue = this.searchValue;
					}
					if (type == 'date') {
						this.queryMoney.dateSearchValue = this.dateSearchValue;
					}
					if (type = 'change') {
						this.queryMoney.searchValue = this.searchValue;
						this.queryMoney.dateSearchValue = this.dateSearchValue;
					}
				}
				if (this.currentNav == 3) {
					if (type == 'search') {
						this.queryBill.searchValue = this.searchValue;
					}
					if (type == 'date') {
						this.queryBill.dateSearchValue = this.dateSearchValue;
					}
					if (type = 'change') {
						this.queryBill.searchValue = this.searchValue;
						this.queryBill.dateSearchValue = this.dateSearchValue;
					}
				}
			},
			search() {
				this.update('search')
			},
			openBillAction(obj) {
				this.currentItem = obj.currentItem
				this.currentBill = obj.currentBill
				if (this.currentBill.title === '待办事项') {
					this.$tab.navigateTo(
						`/pages/detail/billDetail?billId=${this.currentBill.id}&cellId=${this.currentItem.id}`
					)
				} else {
					if (this.currentItem.status === 1) {
						this.$refs.uToast.show({
							title: `该请单项已完成`,
							type: 'success',
						})
					} else {
						this.billActionShow = true
					}
				}
			},
			updateBillCell() {
				updateBillCell(this.currentItem).then(res => {
					uni.startPullDownRefresh()
				})
			},
			settingOfBillOption(index) {
				console.log(`点击了第${index + 1}项，内容为：${this.billActionList[index].text}`)
				if (index === 0 && this.currentItem.status === 0) {
					this.currentItem.status = 1;
				} else if (index === 1 && this.currentItem.status === 1) {
					this.currentItem.status = 0;
				} else {
					this.$refs.uToast.show({
						title: `该清单项状态重复`,
						type: 'warning',
					});
					return
				}
				this.updateBillCell()
				if (this.currentBill.cellListOfSimples.every(cell => cell.status === 1)) {
					this.currentBill.status = 1; // 当每条 item 的 cells 的 status 都为 1 时，调用 getBotbilllist 方法
				} else {
					this.currentBill.status = 0;
				}
			},
			// 手动触发下拉刷新事件
			clickToRefresh() {
				uni.startPullDownRefresh();
			},
			// swiper切换时触发的事件
			swiperChange(e) {
				this.currentNav = e.detail.current;
			},
			// 日期修改
			change(e) {
				this.dateSearchValue = e.result
				this.update('date')
			},
			// 音乐界面跳转
			openMusic() {
				uni.navigateTo({
					url: '/pages/music/music'
				})
			},
			// 我的界面跳转
			pageToMine() {
				uni.switchTab({
					url: '/pages/mine/index'
				})
			},
			// 变换内容类型
			changeContentType(index) {
				this.currentNav = index;
				this.reset()
				this.update('change')
			},
			// 修改日期
			changeDateType(index) {
				this.currentDate = index;
				if (index == 1) {
					this.dateShow = true
				} else {
					this.dateSearchValue = ''
				}
			},
			// 日常功能：预览、点赞、评论
			openImage(obj) {
				if (obj.sysfileInfo && obj.sysfileInfo.length > 0) {
					this.content = obj.sysfileInfo.map(item => item.fileUrl)
					uni.previewImage({
						urls: this.content,
						current: obj.currentImages
					});
				} else {
					this.currentDaily = obj.actionObj
					this.dailyActionShow = true
				}
			},
			// 干饭功能：预览
			openExtend(obj) {
				console.log(obj)
				this.content = obj.sysFileInfos.map(item => item.fileUrl)
				uni.previewImage({
					urls: this.content,
					current: 0
				});
			},
			// 钱袋子功能：刷新、操作额度
			refresh(obj) {
				this.whispersFormData = {}
				this.selectedId = obj.id
				if (obj.type != 1) {
					this.updateConsumption()
				}
				this.whispersShow = true
			},
			// 日常功能：操作拦
			settingOfDailyOption(index) {
				console.log(`点击了第${index + 1}项，内容为：${this.dailyActionList[index].text}`)
				if (index === 0) {
					this.like(this.currentDaily)
				} else {
					this.$refs.uToast.show({
						title: `模块建设中~`,
						type: 'warning',
					})
				}
			},
			// 日常功能：点赞
			like(obj) {
				if (obj.isLike) {
					obj.isLike = false
				} else {
					obj.isLike = true
				}
				let formData = {
					refDailyId: obj.id,
					publishUserId: obj.userId
				}
				addDailyLike(formData).then(res => {
					if (res.code == 200) {
						console.log("点赞成功")
					} else {
						console.log("点赞失败")
					}
					getDailyLikeList(formData).then(res => {
						obj.likeList = res.rows.map(item => item.nickName).join(',')
					})
				})
			},
			updateConsumption() {
				this.whispersTitle = '为你的钱袋子充电'
				this.isUpdate = true
			},
			addConsumption() {
				this.whispersFormData.botMoneyId = this.selectedId
				if (!this.isUpdate && this.whispersFormData.consumptionTitle && this.whispersFormData
					.consumptionTotal) {
					this.whispersFormData.updateMoney = null
					this.whispersFormData.updateTitle = null
					addConsumption(this.whispersFormData).then(res => {
						if (res.data == 1) {
							this.$modal.msgSuccess("记录成功")
							uni.startPullDownRefresh()
							this.whispersShow = false
						} else {
							this.$refs.uToast.show({
								title: `余额不足以抵扣本次消费`,
								type: 'error',
							})
							this.isSuccess = true
						}
					})
				} else if (this.isUpdate && this.whispersFormData.updateMoney && this.whispersFormData
					.updateTitle) {
					this.whispersFormData.consumptionTitle = this.whispersFormData.updateTitle
					this.whispersFormData.consumptionTotal = this.whispersFormData.updateMoney
					addConsumption(this.whispersFormData).then(res => {
						if (res.data == 1) {
							this.$modal.msgSuccess("提额成功")
							uni.startPullDownRefresh()
							this.whispersShow = false
						} else {
							this.$modal.msgError("请求失败")
						}
					})
				} else {
					this.$refs.uToast.show({
						title: `请填写完整信息后提交`,
						type: 'error',
					})
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.swiper {
		height: 80vh;
	}

	.scroll-view-swiper {
		height: 100%;
		width: 100%;
	}

	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.wrap {
		padding: 15rpx 15rpx;
	}

	.u-row {
		margin: 40rpx 0;
	}

	.demo-layout {
		height: 80rpx;
		border-radius: 8rpx;
	}

	.bg-purple {
		background: #d3dce6;
	}

	.bg-purple-light {
		background: #e5e9f2;
	}

	.bg-purple-dark {
		background: #99a9bf;
	}

	.u-card-wrap {
		background-color: $u-bg-color;
		padding: 1px;
	}

	.u-body-item {
		font-size: 32rpx;
		color: #333;
		padding: 20rpx 10rpx;
	}

	.u-body-item image {
		width: 120rpx;
		flex: 0 0 120rpx;
		height: 120rpx;
		border-radius: 8rpx;
		margin-left: 12rpx;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		width: 120px;
		height: 120px;
		background-color: #fff;
	}

	.moneyWarp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.moneyRect {
		width: 300px;
		background-color: #fff;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	}

	.moneyTitle {
		font-size: 18px;
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
	}

	.moneyContent {
		height: 80%;
		display: flex;
		flex-direction: column;
		padding: 5rpx 15rpx;
	}

	.button-group {
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}

	button::after {
		border: none;
	}

	.swiper-item {
		width: 100%;
	}
</style>